<template>
  <div class="document-access-rules">
    <div class="header-actions">
      <h1>文档访问控制</h1>
      <el-button type="primary" @click="openDialog('add')">添加规则</el-button>
    </div>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>访问控制说明</span>
        </div>
      </template>
      <div class="help-content">
        <p>访问控制规则用于限制用户对验证记录文档的访问权限。您可以基于角色或用户设置规则，确保敏感信息的安全。</p>
        <ul class="help-list">
          <li>规则按优先级从高到低排序，系统会应用第一个匹配的规则</li>
          <li>如果没有匹配的规则，默认情况下用户无法访问文档</li>
          <li>为了最大化安全性，建议使用最小权限原则进行配置</li>
        </ul>
      </div>
    </el-card>

    <el-table v-loading="loading" :data="rulesList" border style="width: 100%">
      <el-table-column prop="name" label="规则名称" min-width="150" />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column label="权限范围" min-width="120">
        <template #default="{ row }">
          <el-tag>{{ getScopeText(row.scope) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="可见范围" min-width="150">
        <template #default="{ row }">
          <div v-if="row.scope === 'role'">
            <el-tag v-for="role in row.roles" :key="role" class="tag-item" type="info">{{ role }}</el-tag>
          </div>
          <div v-else-if="row.scope === 'user'">
            <el-tag v-for="user in row.users" :key="user" class="tag-item" type="info">{{ user }}</el-tag>
          </div>
          <span v-else>全部用户</span>
        </template>
      </el-table-column>
      <el-table-column label="权限类型" min-width="120">
        <template #default="{ row }">
          <el-tag :type="getPermissionTypeClass(row.permissionType)">
            {{ getPermissionTypeText(row.permissionType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优先级" width="80" align="center">
        <template #default="{ row }">
          {{ row.priority }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.enabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="openDialog('edit', row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑规则对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加规则' : '编辑规则'"
      width="50%"
      :before-close="handleCloseDialog"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleRules"
        label-width="100px"
        class="rule-form"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="ruleForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入描述"
          />
        </el-form-item>
        
        <el-form-item label="权限范围" prop="scope">
          <el-radio-group v-model="ruleForm.scope">
            <el-radio label="all">所有用户</el-radio>
            <el-radio label="role">指定角色</el-radio>
            <el-radio label="user">指定用户</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="角色列表" v-if="ruleForm.scope === 'role'" prop="roles">
          <el-select
            v-model="ruleForm.roles"
            multiple
            collapse-tags
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="用户列表" v-if="ruleForm.scope === 'user'" prop="users">
          <el-select
            v-model="ruleForm.users"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词搜索用户"
            :remote-method="remoteSearchUsers"
            :loading="userSearching"
            style="width: 100%"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="权限类型" prop="permissionType">
          <el-radio-group v-model="ruleForm.permissionType">
            <el-radio label="read">只读</el-radio>
            <el-radio label="read_write">读写</el-radio>
            <el-radio label="full">完全权限</el-radio>
            <el-radio label="none">禁止访问</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="ruleForm.priority" :min="1" :max="100" />
          <span class="priority-hint">值越小优先级越高</span>
        </el-form-item>
        
        <el-form-item label="状态" prop="enabled">
          <el-switch
            v-model="ruleForm.enabled"
            active-text="启用"
            inactive-text="禁用"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="submitRuleForm" :loading="submitting">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getDocumentAccessRules, 
  createDocumentAccessRule, 
  updateDocumentAccessRule, 
  deleteDocumentAccessRule 
} from '@/api/vulnVerification'

// 表格数据
const loading = ref(false)
const rulesList = ref([])

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const submitting = ref(false)

// 表单引用
const ruleFormRef = ref(null)

// 用户搜索
const userSearching = ref(false)
const userOptions = ref([])

// 角色选项
const roleOptions = [
  { value: 'admin', label: '管理员' },
  { value: 'security_admin', label: '安全管理员' },
  { value: 'security_analyst', label: '安全分析师' },
  { value: 'operator', label: '操作员' },
  { value: 'viewer', label: '普通查看者' }
]

// 表单数据
const ruleForm = reactive({
  id: '',
  name: '',
  description: '',
  scope: 'all', // 'all', 'role', 'user'
  roles: [],
  users: [],
  permissionType: 'read', // 'read', 'read_write', 'full', 'none'
  priority: 10,
  enabled: true
})

// 表单验证规则
const ruleRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  scope: [
    { required: true, message: '请选择权限范围', trigger: 'change' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change', type: 'array' }
  ],
  users: [
    { required: true, message: '请选择用户', trigger: 'change', type: 'array' }
  ],
  permissionType: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请设置优先级', trigger: 'blur', type: 'number' }
  ]
}

// 获取规则列表
const fetchRulesList = async () => {
  loading.value = true
  try {
    const { data } = await getDocumentAccessRules()
    rulesList.value = data
  } catch (error) {
    console.error('获取访问控制规则列表失败', error)
    ElMessage.error('获取访问控制规则列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限范围文本
const getScopeText = (scope) => {
  const scopeMap = {
    all: '所有用户',
    role: '指定角色',
    user: '指定用户'
  }
  return scopeMap[scope] || '未知'
}

// 获取权限类型文本
const getPermissionTypeText = (type) => {
  const typeMap = {
    read: '只读',
    read_write: '读写',
    full: '完全权限',
    none: '禁止访问'
  }
  return typeMap[type] || '未知'
}

// 获取权限类型样式
const getPermissionTypeClass = (type) => {
  const typeClassMap = {
    read: 'info',
    read_write: 'success',
    full: 'warning',
    none: 'danger'
  }
  return typeClassMap[type] || ''
}

// 远程搜索用户
const remoteSearchUsers = async (query) => {
  if (query.length < 2) return
  
  userSearching.value = true
  try {
    // 模拟API请求
    setTimeout(() => {
      userOptions.value = [
        { value: 'user1', label: '用户1 (user1@example.com)' },
        { value: 'user2', label: '用户2 (user2@example.com)' },
        { value: 'user3', label: '用户3 (user3@example.com)' }
      ].filter(item => item.label.toLowerCase().includes(query.toLowerCase()))
      userSearching.value = false
    }, 500)
    
    // 实际项目中，应该调用API
    // const { data } = await searchUsers(query)
    // userOptions.value = data.map(user => ({
    //   value: user.id,
    //   label: `${user.name} (${user.email})`
    // }))
  } catch (error) {
    console.error('搜索用户失败', error)
    ElMessage.error('搜索用户失败')
  } finally {
    userSearching.value = false
  }
}

// 打开对话框
const openDialog = (type, row) => {
  dialogType.value = type
  resetForm()
  
  if (type === 'edit' && row) {
    ruleForm.id = row.id
    ruleForm.name = row.name
    ruleForm.description = row.description
    ruleForm.scope = row.scope
    ruleForm.roles = [...(row.roles || [])]
    ruleForm.users = [...(row.users || [])]
    ruleForm.permissionType = row.permissionType
    ruleForm.priority = row.priority
    ruleForm.enabled = row.enabled
  }
  
  dialogVisible.value = true
}

// 关闭对话框
const handleCloseDialog = () => {
  if (submitting.value) return
  
  dialogVisible.value = false
}

// 重置表单
const resetForm = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
  
  ruleForm.id = ''
  ruleForm.name = ''
  ruleForm.description = ''
  ruleForm.scope = 'all'
  ruleForm.roles = []
  ruleForm.users = []
  ruleForm.permissionType = 'read'
  ruleForm.priority = 10
  ruleForm.enabled = true
}

// 提交表单
const submitRuleForm = () => {
  if (ruleFormRef.value) {
    // 根据scope动态添加验证规则
    if (ruleForm.scope === 'role') {
      if (ruleForm.roles.length === 0) {
        ElMessage.warning('请至少选择一个角色')
        return
      }
    } else if (ruleForm.scope === 'user') {
      if (ruleForm.users.length === 0) {
        ElMessage.warning('请至少选择一个用户')
        return
      }
    }
    
    ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        submitting.value = true
        try {
          const formData = {
            name: ruleForm.name,
            description: ruleForm.description,
            scope: ruleForm.scope,
            permissionType: ruleForm.permissionType,
            priority: ruleForm.priority,
            enabled: ruleForm.enabled
          }
          
          // 根据scope添加相应的字段
          if (ruleForm.scope === 'role') {
            formData.roles = ruleForm.roles
          } else if (ruleForm.scope === 'user') {
            formData.users = ruleForm.users
          }
          
          if (dialogType.value === 'add') {
            // 创建规则
            await createDocumentAccessRule(formData)
            ElMessage.success('规则创建成功')
          } else {
            // 更新规则
            formData.id = ruleForm.id
            await updateDocumentAccessRule(formData)
            ElMessage.success('规则更新成功')
          }
          
          dialogVisible.value = false
          fetchRulesList()
        } catch (error) {
          console.error('保存规则失败', error)
          ElMessage.error('保存规则失败')
        } finally {
          submitting.value = false
        }
      }
    })
  }
}

// 修改规则状态
const handleStatusChange = async (row) => {
  try {
    await updateDocumentAccessRule({
      id: row.id,
      enabled: row.enabled
    })
    ElMessage.success(`规则已${row.enabled ? '启用' : '禁用'}`)
  } catch (error) {
    // 恢复原状态
    row.enabled = !row.enabled
    console.error('修改规则状态失败', error)
    ElMessage.error('修改规则状态失败')
  }
}

// 删除规则
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该规则吗？此操作不可逆', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDocumentAccessRule(row.id)
      ElMessage.success('删除成功')
      fetchRulesList()
    } catch (error) {
      console.error('删除规则失败', error)
      ElMessage.error('删除规则失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 组件挂载时加载数据
onMounted(() => {
  fetchRulesList()
})
</script>

<style lang="scss" scoped>
.document-access-rules {
  padding: 20px;
  
  .help-content {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
  }
  
  .tag-item {
    margin-left: 4px;
  }
}
</style> 